package com.chao.utils;

import com.chao.model.Meta;
import com.chao.model.Pagination;
import com.chao.model.ResponseVO;
import com.chao.model.ResultConsts;

import java.io.Serializable;
import com.github.pagehelper.PageInfo;

/**
 * @author Luck Chao
 * @Date: 2021/12/09
 */
public class ResultUtils implements Serializable {

    /**
     * message：操作成功
     * @return
     */
    public static ResponseVO success() {
        return createResponseVO(null, "操作成功！", ResultConsts.SUCCESS_STATUS);
    }

    /**
     * @param message 提示信息
     * @return
     */
    public static ResponseVO success(String message) {
        return success(null, message);
    }



    /**
     * @param data 业务数据
     * @return
     */
    public static ResponseVO success(Object data) {
        return createResponseVO(data, "操作成功！", ResultConsts.SUCCESS_STATUS);
    }

    /**
     * 前端，吐丝提示
     * @param data 返回数据
     * @param message 业务数据
     * @return
     */
    public static ResponseVO success(Object data, String message) {
        return createResponseVO(data, message, ResultConsts.SUCCESS_STATUS);
    }


    /**
     * @param message 信息描述
     * @return
     */
    public static ResponseVO error(String message) {
        return createResponseVO(false, message, ResultConsts.ERROR_STATUS);
    }



    private static ResponseVO createResponseVO(Object data, String message, Integer code) {
        ResponseVO responseVO = new ResponseVO();
        responseVO.setMessage(message);
        responseVO.setCode(code);

        Meta meta = new Meta();
        if (null != data && PageInfo.class.isAssignableFrom(data.getClass())) {
            PageInfo<?> pageInfo = (PageInfo<?>) data;
            Pagination pagination = new Pagination();
            pagination.setPage(pageInfo.getPageNum());
            pagination.setLimit(pageInfo.getPageSize());
            pagination.setTotal(pageInfo.getTotal());
            pagination.setPages(pageInfo.getPages());
            meta.setPagination(pagination);

            responseVO.setData(pageInfo.getList());
        } else {
            responseVO.setData(data);
        }
//        HeaderContext headerContext = HeaderContextHolder.get();
//        meta.setTraceId(headerContext.getTraceId());
        responseVO.setMeta(meta);
        return responseVO;
    }


}
